package com.chenyi.framework.web.service;

import com.chenyi.common.core.domain.entity.SysAdmin;
import com.chenyi.common.core.domain.model.LoginAdmin;
import com.chenyi.common.enums.UserStatus;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.exception.MessageException;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.system.service.ISysAdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author wangkh
 */
@Service
public class AdminDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(AdminDetailsServiceImpl.class);

    @Autowired
    private ISysAdminService adminService;

    @Autowired
    private AdminPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysAdmin admin = adminService.selectAdminByUserName(username);
        if (StringUtils.isNull(admin))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(admin.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new MessageException("对不起，您的账号：" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(admin.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new MessageException("对不起，您的账号：" + username + " 已停用");
        }

        return createLoginAdmin(admin);
    }

    public UserDetails createLoginAdmin(SysAdmin admin)
    {
        return new LoginAdmin(admin, permissionService.getMenuPermission(admin));
    }
}
